package server

import (
	"encoding/json"
	"gitee.com/godY/daminghu-cli/cfg"
	"gitee.com/godY/daminghu-cli/common"
	"gitee.com/godY/daminghu-cli/handler"
	"gitee.com/godY/daminghu-cli/handler/demo"
	"github.com/astaxie/beego"
	"io/ioutil"
	"os"
	"github.com/astaxie/beego/logs"
)

var CreateHandler handler.HandlerTablesFunc = func(table []*common.Table) {

	beego.Debug("CreateHandler")
	//t := cfg.Cfg.GetServerTempPath() + time.UnixNow() + "/"
	//os.MkdirAll(t, os.ModePerm)
	//handler.DownloadFile(common.EaseWebZipUrl, t+"easy.zip")
	//handler.Unzip(t+"easy.zip", t)

	if true {
		beego.Debug("Start Prepare ......")
		req := demo.CreateReq{table}
		tableBytes, e := json.Marshal(req)
		if e != nil {
			panic(e)
		}
		now := common.GetNowTimeYYYYMMDDhhmmss()
		tempPath := cfg.Cfg.GetServerTempPath() + now + "/"
		distPath := cfg.Cfg.DistPath
		e = os.MkdirAll(tempPath, os.ModePerm)

		if e != nil {
			panic(e)
		}
		dataFilePath := tempPath + "data.json"
		e = ioutil.WriteFile(dataFilePath, tableBytes, os.ModePerm)
		if e != nil {
			panic(e)
		}

		//dumpFilePath := tempPath + "dump.sql"
		//e = db.Engine.DumpAllToFileYasenagat(dumpFilePath)

		filenames := []string{"data", "cfg"}
		filepaths := []string{dataFilePath, common.CmdParam.CfgPath}

		if e != nil {
			beego.Error(e)
		} else {
			//filenames = append(filenames, "sql")
			//filepaths = append(filepaths, dumpFilePath)
		}
		params := make(map[string]string)
		params["build"] = common.CmdParam.BuildType
		params["email"] = common.CmdParam.Email
		beego.Debug("Prepare Done!")

		beego.Debug("Start Build ......")
		resp, e := handler.PostFiles(common.CreateAllUrl, params, filenames, filepaths)

		if e != nil {
			panic(e)
		}

		resBytes, e := ioutil.ReadAll(resp.Body)

		if resp.StatusCode != 200 {
			logs.Error("response => ", string(resBytes))
			panic(resp.Status)
		}

		resObj := demo.CreateRes{}
		e = json.Unmarshal(resBytes, &resObj)
		if e != nil {
			panic(e)
		}

		svrZipPath := tempPath + cfg.Cfg.GetServerProjcetName() + ".zip"
		webZipPath := tempPath + cfg.Cfg.GetWebProjcetName() + ".zip"
		easyWebZipPath := tempPath + "easyweb.zip"

		beego.Debug("Build Done !")

		beego.Debug("Start Write ......")

		if resObj.Result == 0 {

			token := make(chan int, 3)
			go func() {
				//defer func() {
				//	token <- 1
				//}()
				beego.Debug("Start Write Svr......")
				if resObj.Body.SvrZipUrl != "" {
					handler.DownloadFile(resObj.Body.SvrZipUrl, svrZipPath)

					handler.Unzip(svrZipPath, distPath)
				}
				beego.Debug("Write Svr Done!")
				token <- 1
			}()

			go func() {
				//defer func() {
				//	token <- 1
				//}()
				beego.Debug("Start Write Web......")
				if resObj.Body.WebZipUrl != "" {
					handler.DownloadFile(resObj.Body.WebZipUrl, webZipPath)

					handler.Unzip(webZipPath, distPath)
				}
				beego.Debug("Write Web Done!")
				token <- 1
			}()

			go func() {
				beego.Debug("Start Write EasyWeb......")
				handler.DownloadFile(common.EaseWebZipUrl, easyWebZipPath)
				handler.Unzip(easyWebZipPath, distPath)
				beego.Debug("Write EasyWeb Done!")
				token <- 1
			}()

			<-token
			<-token
			<-token
		}
		beego.Debug("Write Done!")
		beego.Debug(resObj.Message)

	}

}
